using System.Data;
using System.Linq;

namespace DataScripter.Scripting.Compare.DataTables.Structure
{
    public class DataTableStructureComparer
    {
        private System.Data.DataTable Table1 { get; set; }
        private System.Data.DataTable Table2 { get; set; }

        public DataTableStructureComparer(System.Data.DataTable table1, System.Data.DataTable table2)
        {
            Table1 = table1;
            Table2 = table2;
        }

        public DataTableStructureComparisonResult Compare()
        {
            DataTableStructureComparisonResult result = new DataTableStructureComparisonResult();
            CompareColumns(result);
            //TODO: compare Table1.ChildRelations
            //TODO: compare Table1.Constraints
            //TODO: compare Table1.ParentRelations
            //TODO: compare Table1.PrimaryKey
            //TODO: compare Table1.TableName
            return result;
        }

        private void CompareColumns(DataTableStructureComparisonResult result)
        {
            foreach (DataColumn column1 in Table1.Columns)
            {
                DataColumn column2 = ColumnExists(Table2, column1);
                if (column2 == null)
                    result.ColumnsToInsert.Add(column1.ColumnName);
                else
                {
                    DataColumnStructureComparisonResult comparisonResult = CompareColumns(column1, column2);
                    if (!comparisonResult.IsSame())
                    {
                        result.ColumnsToUpdate.Add(column1.ColumnName, comparisonResult);
                    }
                }
            }
            foreach (DataColumn column2 in Table2.Columns)
            {
                DataColumn column1 = ColumnExists(Table1, column2);
                if (column1 == null)
                    result.ColumnsToRemove.Add(column2.ColumnName);
            }
        }

        private DataColumnStructureComparisonResult CompareColumns(DataColumn column1, DataColumn column2)
        {
            DataColumnStructureComparer comparer = new DataColumnStructureComparer(column1, column2);
            DataColumnStructureComparisonResult comparisonResult = comparer.Compare();
            return comparisonResult;
        }

        private DataColumn ColumnExists(System.Data.DataTable table, DataColumn column)
        {
            return table.Columns.Cast<DataColumn>().FirstOrDefault(dataColumn => dataColumn.ColumnName == column.ColumnName);
        }
    }
}